#include "ui_favorites.h"
#include "service_favorites.h" 
#include "service_player.h"
#include "ui_player.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

// 全局变量，用于其他模块可以加载此屏幕
lv_obj_t *ui_favorites_screen;

//初始化一块黑色幕布
extern lv_obj_t *ui_loading_curtain;

// 声明播放器屏幕，以便我们可以返回
extern lv_obj_t *ui_player_screen;

// 当点击“返回”按钮时
static void back_to_player_cb(lv_event_t *e) {
    

    // 显示黑色幕布
    if (ui_loading_curtain) {
        lv_obj_clear_flag(ui_loading_curtain, LV_OBJ_FLAG_HIDDEN);
    }

    if (ui_player_screen)
    {
        lv_scr_load(ui_player_screen); // 加载播放器屏幕
    }
    //清理屏幕
    if (ui_favorites_screen)
    {
        //删除屏幕及其子控件
        lv_obj_del(ui_favorites_screen);
        //把屏幕变为空避免野指针
        ui_favorites_screen = NULL;
    }
      
     //命令业务逻辑层，重新播放我们离开前的那个视频
    service_player_replay_current();
}

// 当点击收藏列表中的某一项时
static void favorite_item_click_cb(lv_event_t *e) {
    const char* url = (const char*)lv_event_get_user_data(e);
    printf("点击了收藏夹中的视频: %s\n", url);
    
     // 切换回播放器屏幕
    if (ui_player_screen) {
        lv_scr_load(ui_player_screen);
    }

    // 删除收藏夹屏幕
    if (ui_favorites_screen) {
        lv_obj_del(ui_favorites_screen);
        ui_favorites_screen = NULL;
    }
    
    // 开始执行后台下载
    service_player_start_favorite_playback(url);
    
    // 命令播放器UI层进入“等待收藏视频加载”的状态
    start_favorite_loading_flow(url);
}

// 创建收藏列表界面
void ui_favorites_screen_create(void) {

    printf("__%d__\n",__LINE__);
    //lv_scr_load(ui_favorites_screen); 
    printf("__%d__\n",__LINE__);
    if (ui_favorites_screen) {
        // 如果已经创建，只需要刷新内容即可
        lv_obj_clean(lv_obj_get_child(ui_favorites_screen, 0)); // 清理旧列表
    } else {
        // 首次创建
        ui_favorites_screen = lv_obj_create(NULL);
    }

    lv_obj_t *list = lv_list_create(ui_favorites_screen);
    lv_obj_set_size(list, lv_pct(100), lv_pct(100));
    lv_obj_center(list);

    // 添加返回按钮
    lv_obj_t *btn_back = lv_list_add_btn(list, LV_SYMBOL_LEFT, "Back to Player");
    lv_obj_add_event_cb(btn_back, back_to_player_cb, LV_EVENT_CLICKED, NULL);

    // --- 从文件中读取收藏并添加到列表 ---
    FILE *fp = fopen(FAVORITES_FILE_PATH, "r");
    if (fp == NULL) {
        lv_list_add_text(list, "No favorites yet.");
        // 注意：这里需要确保在没有返回按钮的情况下也能返回，比如通过手势
        return;
    }

    char *line = NULL;
    size_t len = 0;
    while (getline(&line, &len, fp) != -1) {
        line[strcspn(line, "\n")] = 0;
        if (strlen(line) > 0) { // 忽略空行
            char *url_copy = strdup(line); 
            lv_obj_t *btn_item = lv_list_add_btn(list, LV_SYMBOL_VIDEO, url_copy);
            lv_obj_add_event_cb(btn_item, favorite_item_click_cb, LV_EVENT_CLICKED, url_copy);
        }
    }
    fclose(fp);
    if (line) free(line);
}